package csel.model;

import java.util.concurrent.ConcurrentLinkedQueue;

import org.apache.log4j.Logger;

public class ChronoTrigger implements Runnable, java.io.Serializable
{
	private static final long serialVersionUID = 5L;
	
	private static final Logger logger = Logger.getLogger("csel.model");
	
	private final ConcurrentLinkedQueue<Ticked> tickList;
	private volatile boolean go;
	private volatile boolean paused;
	private transient Thread thread;

	public ChronoTrigger()
	{
		tickList = new ConcurrentLinkedQueue<Ticked>();
		go = true;
		paused = false;
	}

	public boolean addTicked(Ticked t)
	{
		// adds new Ticked to beginning of the tickList
		tickList.add(t);
		return (true);
	}

	public boolean removeTicked(Ticked t)
	{
		return (tickList.remove(t));
	}

	public void start()
	{
		thread = new Thread(this);
		thread.start();
		
		logger.info("ChronoTrigger started.");
	}

	public void stop()
	{
		logger.info("ChronoTrigger dying...");
		
		go = false;
	}

	public void pause()
	{
		paused = true;
	}

	public void unpause()
	{
		paused = false;
		synchronized (this)
		{
			notifyAll();
		}
	}

	public void clearTickeds()
	{
		tickList.clear();
	}

	public void run()
	{
		while (go)
		{
			// cycles through all Tickeds in tickList every 0.1 seconds until
			// stop is called
			try
			{
				Thread.sleep(10);
			} catch (InterruptedException e)
			{

			}
			if (paused)
			{
				synchronized (this)
				{
					while (paused)
					{
						try
						{
							wait();
						} catch (InterruptedException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
			for (Ticked t : tickList)
				t.tick();
		}

		logger.info("ChronoTrigger died.");
	}

}
